package handlers

import (
	"backend/internal/database"
	"backend/internal/dto"
	"backend/models"
	"backend/pkg/log"
	"backend/pkg/utils"
	"net/http"
	"time"

	"github.com/gin-gonic/gin"
	"golang.org/x/crypto/bcrypt"
)

func Login(c *gin.Context) {
	startTime := time.Now()
	var req dto.LoginRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		log.Error("请求参数绑定失败: %v", err)
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		log.RequestLog(c, startTime, "请求参数绑定失败")
		return
	}

	log.Debug("收到登录请求: email=%s", req.Email)

	var user models.User
	if result := database.DB.Where("email = ?", req.Email).First(&user); result.Error != nil {
		log.Warning("用户不存在: %s", req.Email)
		c.JSON(http.StatusUnauthorized, gin.H{"error": "邮箱或密码错误"})
		log.RequestLog(c, startTime, "用户不存在")
		return
	}

	if err := bcrypt.CompareHashAndPassword([]byte(user.Password), []byte(req.Password)); err != nil {
		log.Warning("密码错误: %s", req.Email)
		c.JSON(http.StatusUnauthorized, gin.H{"error": "邮箱或密码错误"})
		log.RequestLog(c, startTime, "密码错误")
		return
	}

	token, err := utils.GenerateToken(user.ID)
	if err != nil {
		log.Error("Token生成失败: %v", err)
		c.JSON(http.StatusInternalServerError, gin.H{"error": "Token生成失败"})
		log.RequestLog(c, startTime, "Token生成失败")
		return
	}

	c.JSON(http.StatusOK, dto.LoginResponse{
		Token: token,
		User: struct {
			ID    uint   `json:"id"`
			Name  string `json:"name"`
			Email string `json:"email"`
		}{
			ID:    user.ID,
			Name:  user.Name,
			Email: user.Email,
		},
	})

	log.Info("用户登录成功: id=%d, email=%s", user.ID, user.Email)
	log.RequestLog(c, startTime, "登录成功")
}
